package top.go2do.tagCategory.business.category.service;

import jakarta.persistence.criteria.Predicate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import top.go2do.common.dao.ApplicationRepository;
import top.go2do.common.dao.CategoryRepository;
import top.go2do.common.dao.UserRepository;
import top.go2do.common.module.ApplicationPO;
import top.go2do.common.module.CategoryPO;
import top.go2do.common.module.UserPO;
import top.go2do.common.module.pageQuery.PageResult;
import top.go2do.common.utils.IdUtils;
import top.go2do.common.utils.VersionUtils;
import top.go2do.tagCategory.business.category.module.*;
import top.go2do.tagCategory.exception.TagCategoryErrorCode;
import top.go2do.tagCategory.exception.TagCategoryException;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description
 * @Author xingyj
 * @CreateTime 2025/6/18 14:14
 */
@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryRepository categoryRepository;

    @Autowired
    private IdUtils idUtils;

    @Autowired
    private ApplicationRepository applicationRepository;

    @Autowired
    private UserRepository userRepository;

    @Override
    public CategoryListVO create(CategoryCreateForm createForm) {
        String appId = createForm.getAppId();
        String entityCode = createForm.getEntityCode();
        String categoryName = createForm.getCategoryName();
        Long parentId = createForm.getParentId();
        CategoryPO categoryPO = categoryRepository.findByAppIdAndEntityCodeAndParentIdAndCategoryNameAndCreatedBy(appId, entityCode, parentId, categoryName, createForm.getUserId());
        if (categoryPO != null) {
            throw new TagCategoryException(TagCategoryErrorCode.CATEGORY_NAME_EXIST);
        }
        categoryPO = new CategoryPO();
        categoryPO.setAppId(appId);
        BeanUtils.copyProperties(createForm, categoryPO);
        Long categoryId = idUtils.getSnowflakeId();
        Long userId = createForm.getUserId();

        categoryPO.setCategoryId(categoryId);
        categoryPO.setCreatedBy(userId);
        categoryPO.setUpdatedBy(userId);
        String operator = String.valueOf(createForm.getUserId());
        String version = VersionUtils.generateVersion(categoryPO, operator);
        categoryPO.setVersion(version);
        categoryRepository.save(categoryPO);
        return this.getById(categoryId);
    }

    @Override
    public void modifyById(CategoryModifyForm modifyForm) {
        Long categoryId = modifyForm.getCategoryId();
        CategoryPO categoryPO = this.getPOById(categoryId);
        String categoryName = modifyForm.getCategoryName();
        String entityCode = modifyForm.getEntityCode();
        Long parentId = modifyForm.getParentId();
        Integer sort = modifyForm.getSort();
        String appId = categoryPO.getAppId();
        if (StringUtils.hasText(categoryName)) {
            CategoryPO target = categoryRepository.findByAppIdAndEntityCodeAndParentIdAndCategoryNameAndCreatedBy(appId, entityCode, parentId, categoryName, modifyForm.getUserId());
            if (target != null && !target.getCategoryId().equals(categoryId)) {
                throw new TagCategoryException(TagCategoryErrorCode.CATEGORY_NAME_EXIST);
            }
            categoryPO.setCategoryName(categoryName);
        }
        categoryPO.setParentId(parentId);
        categoryPO.setUpdatedBy(modifyForm.getUserId());
        if (sort != null) {
            categoryPO.setSort(sort);
        }

        String operator = String.valueOf(modifyForm.getUserId());
        String version = VersionUtils.generateVersion(categoryPO, operator);
        categoryPO.setVersion(version);
        categoryRepository.save(categoryPO);
    }

    @Override
    public void removeById(Long id) {
        this.getPOById(id);
        categoryRepository.deleteById(id);
    }

    @Override
    public CategoryListVO getById(Long id) {
        CategoryPO categoryPO = getPOById(id);
        List<CategoryListVO> list = po2vo(List.of(categoryPO));
        return list.get(0);
    }

    private CategoryPO getPOById(Long id) {
        CategoryPO categoryPO = categoryRepository.findById(id).orElse(null);
        if (categoryPO == null) {
            throw new TagCategoryException(TagCategoryErrorCode.CATEGORY_ID_NOT_EXIST);
        }
        return categoryPO;
    }

    @Override
    public PageResult<CategoryListVO> pageQuery(CategoryQueryCondition condition) {
        Sort.Direction direction = Sort.Direction.fromString(condition.getDirection());
        Sort sort = Sort.by(direction, condition.getOrderBy());

        /**
         * pageNumber 从0开始
         */
        Integer page = condition.getPage() - 1;
        Integer size = condition.getSize();
        Pageable pageable = PageRequest.of(page, size, sort);
        Specification<CategoryPO> spec = (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (condition.getAppId() != null) {
                predicates.add(cb.equal(root.get("appId"), condition.getAppId()));
            }

            if (condition.getUserId() != null) {
                predicates.add(cb.equal(root.get("createdBy"), condition.getUserId()));
            }

            if (condition.getEntityCode() != null) {
                predicates.add(cb.equal(root.get("entityCode"), condition.getEntityCode()));
            }

            if (condition.getParentId() != null) {
                predicates.add(cb.equal(root.get("parentId"), condition.getParentId()));
            }

            if (condition.getStatus() != null) {
                predicates.add(cb.equal(root.get("status"), condition.getStatus()));
            }

            if (condition.getCategoryName() != null) {
                predicates.add(cb.like(root.get("categoryName"), "%" + condition.getCategoryName() + "%"));
            }

            if (condition.getKeyword() != null) {
                Predicate appIdMatch = cb.like(root.get("categoryName"), "%" + condition.getKeyword() + "%");
                Predicate appNameMatch = cb.like(root.get("description"), "%" + condition.getKeyword() + "%");
                predicates.add(cb.or(appIdMatch, appNameMatch)); // 核心修改点
            }
            return cb.and(predicates.toArray(new Predicate[0]));
        };
        Page<CategoryPO> queryResult = categoryRepository.findAll(spec, pageable);
        PageResult<CategoryListVO> pageResult = new PageResult(queryResult.getNumber(), queryResult.getSize(), queryResult.getTotalElements(), queryResult.getTotalPages());
        pageResult.setList(po2vo(queryResult.getContent()));
        return pageResult;
    }

    @Override
    public List<CategoryListVO> listAll(CategoryQueryAllCondition condition) {
        Sort.Direction direction = Sort.Direction.fromString(condition.getDirection());
        Sort sort = Sort.by(direction, condition.getOrderBy());

        Specification<CategoryPO> spec = (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();

            if (condition.getAppId() != null) {
                predicates.add(cb.equal(root.get("appId"), condition.getAppId()));
            }

            if (condition.getUserId() != null) {
                predicates.add(cb.equal(root.get("createdBy"), condition.getUserId()));
            }

            if (condition.getEntityCode() != null) {
                predicates.add(cb.equal(root.get("entityCode"), condition.getEntityCode()));
            }

            if (condition.getParentId() != null) {
                predicates.add(cb.equal(root.get("parentId"), condition.getParentId()));
            }

            if (condition.getStatus() != null) {
                predicates.add(cb.equal(root.get("status"), condition.getStatus()));
            }

            if (condition.getCategoryName() != null) {
                predicates.add(cb.like(root.get("categoryName"), "%" + condition.getCategoryName() + "%"));
            }

            if (condition.getKeyword() != null) {
                Predicate appIdMatch = cb.like(root.get("categoryName"), "%" + condition.getKeyword() + "%");
                Predicate appNameMatch = cb.like(root.get("description"), "%" + condition.getKeyword() + "%");
                predicates.add(cb.or(appIdMatch, appNameMatch)); // 核心修改点
            }
            return cb.and(predicates.toArray(new Predicate[0]));
        };
        return po2vo(categoryRepository.findAll(spec, sort));
    }

    @Override
    public List<CategoryListVO> po2vo(List<CategoryPO> list) {
        Set<String> appIdSet = new HashSet<>();
        Set<Long> userIdSet = new HashSet<>();
        for (CategoryPO po : list) {
            appIdSet.add(po.getAppId());
            userIdSet.add(po.getCreatedBy());
            userIdSet.add(po.getUpdatedBy());
        }
        List<ApplicationPO> appList = applicationRepository.findAllById(appIdSet);
        List<UserPO> userList = userRepository.findAllById(userIdSet);
        Map<String, String> appId2NameMap;
        Map<Long, String> userId2NameMap;
        if (appList != null) {
            appId2NameMap = appList.stream().collect(Collectors.toMap(ApplicationPO::getAppId, ApplicationPO::getAppName));
        } else {
            appId2NameMap = new HashMap<>(0);
        }

        if (userList != null) {
            userId2NameMap = userList.stream().collect(Collectors.toMap(UserPO::getUserId, UserPO::getUsername));
        } else {
            userId2NameMap = new HashMap<>(0);
        }
        List<CategoryListVO> voList = list.stream().map(po -> {
            CategoryListVO vo = new CategoryListVO();
            BeanUtils.copyProperties(po, vo);
            vo.setAppName(appId2NameMap.get(po.getAppId()));
            vo.setCreatedByName(userId2NameMap.get(po.getCreatedBy()));
            vo.setUpdatedByName(userId2NameMap.get(po.getUpdatedBy()));
            vo.setCategoryId(String.valueOf(po.getCategoryId()));
            if (po.getParentId() != null) {
                vo.setParentId(String.valueOf(po.getParentId()));
            }
            vo.setUpdatedBy(String.valueOf(po.getUpdatedBy()));
            vo.setCreatedBy(String.valueOf(po.getCreatedBy()));
            return vo;
        }).toList();
        return voList;
    }
}
